import os
import logging
import httplib2

from apiclient.discovery import build
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from tp_oauth.models import CredentialsModel
from django.conf import settings
from oauth2client import xsrfutil
from oauth2client.client import flow_from_clientsecrets
from oauth2client.django_orm import Storage

# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
# application, including client_id and client_secret, which are found
# on the API Access tab on the Google APIs
# Console <http://code.google.com/apis/console>
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), '../..', 'client_secrets.json')

FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/plus.me',
    # redirect_uri=reverse('auth_return'))
    redirect_uri="http://localhost:8000/tp_oauth/oauth2callback")


# OAuth index page
# login_required is a wrapper verifying if the user is logged in or not
# if the user isn't logged it, he will be redirected to the login page
@login_required
def index(request):
  # Get the user's credentials from local database
  storage = Storage(CredentialsModel, 'id', request.user, 'credential')
  credential = storage.get()
  # If there is no credentials or if credentials are wrong
  if credential is None or credential.invalid == True:
    # generate a token which is going to be validated later
    FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                                                   request.user)
    authorize_url = FLOW.step1_get_authorize_url()
    # Then redirect the user to the remote login page
    return HttpResponseRedirect(authorize_url)
  # If the credential are correct
  else:
    http = httplib2.Http()
    http = credential.authorize(http)
    # Collect the user's Google plus activities
    service = build("plus", "v1", http=http)
    activities = service.activities()
    activitylist = activities.list(collection='public',
                                   userId='me').execute()
    person = service.people().get(userId='me').execute(http=http)
    logging.info(activitylist)
    # Return the formatted webpage
    return render_to_response('tp_oauth/welcome.html', {
                'activitylist': activitylist,'person':person,
                },
                context_instance=RequestContext(request))


@login_required
def auth_return(request):
  # If the token returned by the provider isn't valid, returns a error 400 page
  if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                 request.user):
    return  HttpResponseBadRequest()
  # Otherwise save the new credential to the local database
  credential = FLOW.step2_exchange(request.REQUEST)
  storage = Storage(CredentialsModel, 'id', request.user, 'credential')
  storage.put(credential)
  return HttpResponseRedirect(reverse('tp_oauth_index'))
